package com.dw.web;


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dw.service.EmployeeService;

public class EmployeeServlet extends HttpServlet {

	
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getMethod();
		String m = request.getParameter("m");
		if("ajax".equals(m)){
			ajax(request,response);
		}else{
			
			if("POST".equals(method)){
				saveEmployee(request,response);
			}else if("GET".equals(method)) {
				
				toNewEmployee(request,response);
			}
		}
	}

	

	private void ajax(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.setCharacterEncoding("UTF-8");
		
		String name = request.getParameter("name");
		
		
		
		
		
		PrintWriter out = response.getWriter();
		if("tom".equals(name)) {
			out.print("yes");
		} else {
			out.print("no");
		}
		
		out.flush();
		out.close();
		
	}



	private void toNewEmployee(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		request.getRequestDispatcher("/WEB-INF/views/newEmployee.jsp").forward(request, response);
	}

	private void saveEmployee(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException{
		request.setCharacterEncoding("UTF-8");
		
		String name = request.getParameter("name");
		String password = request.getParameter("password");
		String email = request.getParameter("email");
		String address = request.getParameter("adress");
		String tel = request.getParameter("tel");
		String zhiwei = request.getParameter("zhiwei");
		
		
		
		
			new EmployeeService().saveEmployee(name,password,email,address,tel,zhiwei);
			response.sendRedirect("main.jspx");
		

	}
	
	

}
